package edu.utwente.sem.hrs;

import java.io.*;

/**
 * This class constructs the UI for a chat client. It implements the chat
 * interface in order to activate the display() method. Warning: Some of the
 * code here is cloned in ServerConsole
 * 
 * @author Fran&ccedil;ois B&eacute;langer
 * @author Dr Timothy C. Lethbridge
 * @author Dr Robert Lagani&egrave;re
 * @author Robert Maaskant
 * @author Dennis van der Zwet
 * @version February 2013
 */
public class ClientConsole implements ChatIF
{
  /**
   * The default port to connect on.
   */
  final public static int DEFAULT_PORT = 5555;

  /**
   * The instance of the client that created this ConsoleChat.
   */
  BalieClient client;

  /**
   * Constructs an instance of the ClientConsole UI.
   * 
   * @param host
   *          The host to connect to.
   * @param port
   *          The port to connect on.
   */
  public ClientConsole(String host, int port)
  {
    try
    {
      client = new BalieClient(host, port, this);
    }
    catch (IOException exception)
    {
      System.out.println("Error: Can't setup connection!"
          + " Terminating client.");
      System.exit(1);
    }
  }

  /**
   * This method waits for input from the console. Once it is received, it sends
   * it to the client's message handler.
   */
  public void accept()
  {
    try
    {
      BufferedReader fromConsole = new BufferedReader(new InputStreamReader(
          System.in));
      String message;

      while (true)
      {
        message = fromConsole.readLine();
        client.handleMessageFromClientUI(message);
      }
    }
    catch (Exception ex)
    {
      System.out.println("Unexpected error while reading from console!");
    }
  }

  /**
   * This method overrides the method in the ChatIF interface. It displays a
   * message onto the screen.
   * 
   * @param message
   *          The string to be displayed.
   */
  public void display(String message)
  {
    System.out.println("> " + message);
  }

  /**
   * This method is responsible for the creation of the Client UI.
   * 
   * @param args
   *          [0] The host to connect to.
   */
  public static void main(String[] args)
  {
    String host = "";
    int port = DEFAULT_PORT;
    ; //The port number

    try
    {
      host = args[0];
      try
      {
        port = Integer.parseInt(args[1]);
      }
      catch (ArrayIndexOutOfBoundsException e)
      {
      }
    }
    catch (ArrayIndexOutOfBoundsException e)
    {
      host = "localhost";
    }

    ClientConsole chat = new ClientConsole(host, port);
    chat.accept(); //Wait for console data
  }
}
